package com.zhangye.test.api;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.zhangye.test.model.Admin;
import com.zhangye.test.model.Category;
import com.zhangye.test.model.EasyAr;
import com.zhangye.test.model.Region;
import com.zhangye.test.service.ArCommentService;
import com.zhangye.test.service.CategoryService;
import com.zhangye.test.service.EasyArService;
import com.zhangye.test.service.InfomationService;
import com.zhangye.test.service.RegionService;
import com.zhangye.test.service.SafeSessionService;
import com.zhangye.test.util.HttpUtil;
import com.zhangye.test.util.PageInfo;


/**
 * ar列表
 * 作者： 张叶
 * 创建时间：2018年7月5日  上午9:17:50
 */
@Controller
@RequestMapping("api/ar")
public class ArApi {
	
	@Autowired
	private EasyArService easyArService;
	@Autowired
	private ArCommentService arCommentService;
	@Autowired
	private InfomationService infomationService;
	@Autowired
	private SafeSessionService safeSessionService;
	@Autowired
	private CategoryService categoryService;
	@Autowired
	private RegionService regionService;
	
	
	/**
	 * 新首页推荐
	 * 作者： 张叶
	 * 创建时间：2018年10月31日  上午9:09:35
	 */
	@ResponseBody
	@RequestMapping(value = "/recommendListNew", method = RequestMethod.POST)
	public ApiResult recommendListNew(String lat,String lng) {
		ApiResult result = new ApiResult();
		String where = " and  id in (select easy_ar_id from ar_recommend where region_code = '0')";
		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		if(lat != null && !"".equals(lat) &&
				lng != null && !"".equals(lng)){
	        Region region = getRegionByLocation(String.format("%s,%s", lng, lat));
	        if (region == null) {
	            region = regionService.getRegionByCode("130101");
	        }
	        String regionCode = region.getCode();
			where = " and  id in (select easy_ar_id from ar_recommend where region_code like '" + regionCode + "%')";
			list = easyArService.selectWhere(where);//当前定位
			if(list.size() == 0){//
				regionCode = regionCode.substring(0,regionCode.length()-2) + "01";
				where = " and  id in (select easy_ar_id from ar_recommend where region_code like '" + regionCode + "%')";
				list = easyArService.selectWhere(where);//上级
				if(list.size() == 0){
					where = " and  id in (select easy_ar_id from ar_recommend where region_code = '0')";
				}
			}
		}
		where += "   order by rand() ";
		list = easyArService.selectWhere(where);
		if(list.size() > 0){
			for(int i = 0 ; i < list.size() ; i ++){
				String videoUrl = list.get(i).get("video_url").toString();
				videoUrl = videoUrl.split(",")[0];
				list.get(i).put("video_url", videoUrl);
			}
			result.data.put("arList", list);
			result.msg.status = 0;
			result.msg.desc = "获取成功";
		}else{
			result.msg.status = 1;
			result.msg.desc = "暂无数据";
		}
		return result;
	}	
	
	
	/**
	 * 视频分类列表
	 * 作者： 张叶
	 * 创建时间：2018年10月30日  下午3:37:39
	 */
	@ResponseBody
	@RequestMapping(value = "/categoryList", method = RequestMethod.POST)
	public ApiResult categoryList(HttpServletRequest request,Integer page, Integer limit,String categoryCode) {
		ApiResult result = new ApiResult();
		if(categoryCode != null && !"".equals(categoryCode)){
			// 搜索条件
			String where = "";
			Admin admin = safeSessionService.getCurrent(request);
			if(admin != null && !"".equals(admin)){
				where += " and (not_like_admin_id not like '%," + admin.getId() + ",%'  or not_like_admin_id is null) ";
			}
			where += " and status = 'on' and category_code like '" + categoryCode + "%'";
			PageInfo pageInfo = new PageInfo();
			if (pageInfo.getPage() < 2
					|| pageInfo.getPage() >= pageInfo.getTotalPage()) {
				pageInfo.setCount(0);
			}
			if (limit != null) {// 每页显示条数
				pageInfo.setPageSize(limit);
			}
			if (page != null) {// 当前页
				pageInfo.setPage(page);
			}
			where += " and (video_url like  '%.mp3%' or video_url like '%.mp4%')";
			int count = easyArService.selectByWhereCount(where);
			String order = " order by create_at desc";
			if(count > 200){
				order = " order by rand()";
			}
			where = " 1 = 1 " + where;
			List<Map<String, Object>> list = easyArService.selectByPageCategory(pageInfo, where, order,admin);
			if(list.size() > 0){
				for(int i = 0 ; i < list.size() ; i ++){
					String videoUrl = list.get(i).get("videoUrl").toString();
					videoUrl = videoUrl.split(",")[0];
					list.get(i).put("videoUrl", videoUrl);
					String imageUrl = list.get(i).get("imageUrl").toString();
					imageUrl += "?imageView/2/w/320";
					list.get(i).put("thumUrl", imageUrl);
				}
				result.data.put("ar", list);
				result.data.put("pageInfo", pageInfo.getTotalPage());
				result.msg.status = 0;
				result.msg.desc = "获取成功";
			}else{
				result.msg.status = 1;
				result.msg.desc = "暂无数据";
			}
		}else{
			result.msg.status = 3;
			result.msg.desc = "参数不能为空";
		}
		return result;
	}	
	
	
	/**
	 * 列表
	 * 作者： 张叶
	 * 创建时间：2018年7月25日  上午10:53:33
	 */
	@ResponseBody
	@RequestMapping(value = "/listNew", method = RequestMethod.POST)
	public ApiResult listNew(HttpServletRequest request,Integer page, Integer limit,String order,String lat,String lng) {
		ApiResult result = new ApiResult();
		if(lat != null && !"".equals(lat) && lng != null && !"".equals(lng)){
			if(order != null && !"".equals(order)){
				if("1".equals(order) || "2".equals(order) || "3".equals(order)){
					// 搜索条件
					String where = "1 = 1";
					Admin admin = safeSessionService.getCurrent(request);
					if(admin != null && !"".equals(admin)){
						where += " and (not_like_admin_id not like '%," + admin.getId() + ",%'  or not_like_admin_id is null) ";
					}
					where += " and status = 'on'";
					PageInfo pageInfo = new PageInfo();
					if (pageInfo.getPage() < 2
							|| pageInfo.getPage() >= pageInfo.getTotalPage()) {
						pageInfo.setCount(0);
					}
					if (limit != null) {// 每页显示条数
						pageInfo.setPageSize(limit);
					}
					if (page != null) {// 当前页
						pageInfo.setPage(page);
					}
					if(order.equals("1")){//最新
						order = " order by rand()";
						where += " and DATE_SUB(CURDATE(), INTERVAL 365 DAY) <= DATE(create_at)";
					}else if(order.equals("2")){//热门
						order = " order by give desc";
					}else{//同城
						order = " order by distance";
					}
					where += " and (video_url like  '%.mp3%' or video_url like '%.mp4%')";
					List<Map<String, Object>> list = easyArService.selectByPageApiNew(pageInfo, where, order,lat,lng,admin);
					if(list.size() > 0){
						for(int i = 0 ; i < list.size() ; i ++){
							String videoUrl = list.get(i).get("videoUrl").toString();
							videoUrl = videoUrl.split(",")[0];
							list.get(i).put("videoUrl", videoUrl);
							String imageUrl = list.get(i).get("imageUrl").toString();
							imageUrl += "?imageView/2/w/320";
							list.get(i).put("thumUrl", imageUrl);
						}
						result.data.put("ar", list);
						result.data.put("pageInfo", pageInfo.getTotalPage());
						result.msg.status = 0;
						result.msg.desc = "获取成功";
					}else{
						result.msg.status = 1;
						result.msg.desc = "暂无数据";
					}
				}else{
					result.msg.status = 4;
					result.msg.desc = "参数格式不正确";
				}
			}else{
				result.msg.status = 3;
				result.msg.desc = "参数不能为空";
			}
		}else{
			result.msg.status = 3;
			result.msg.desc = "参数不能为空";
		}
		return result;
	}	
	
	
	
	/**
	 * 列表
	 * 作者： 张叶
	 * 创建时间：2018年7月25日  上午10:53:33
	 */
	@ResponseBody
	@RequestMapping(value = "/list", method = RequestMethod.POST)
	public ApiResult list(HttpServletRequest request,Integer page, Integer limit,String order,String lat,String lng) {
		ApiResult result = new ApiResult();

		if(lat != null && !"".equals(lat) && lng != null && !"".equals(lng)){
			if(order != null && !"".equals(order)){
				if("1".equals(order) || "2".equals(order) || "3".equals(order)){
					// 搜索条件
					String where = "1 = 1";

					Admin admin = safeSessionService.getCurrent(request);
					if(admin != null && !"".equals(admin)){
						where += " and (not_like_admin_id not like '%," + admin.getId() + ",%'  or not_like_admin_id is null) ";
					}
					where += " and status = 'on'";
					PageInfo pageInfo = new PageInfo();
					if (pageInfo.getPage() < 2
							|| pageInfo.getPage() >= pageInfo.getTotalPage()) {
						pageInfo.setCount(0);
					}
					if (limit != null) {// 每页显示条数
						pageInfo.setPageSize(limit);
					}
					if (page != null) {// 当前页
						pageInfo.setPage(page);
					}
					List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
					where += " and (video_url like  '%.mp3%' or video_url like '%.mp4%')";
					if(order.equals("1")){//最新
						order = "";
						where += " and id >= ((SELECT MAX(id) FROM easy_ar)-(SELECT MIN(id) FROM easy_ar)) * RAND() + (SELECT MIN(id) FROM easy_ar) and DATE_SUB(CURDATE(), INTERVAL 30 DAY) <= DATE(create_at)";
						list = easyArService.selectByPageApiNew(pageInfo, where, order,lat,lng,null);
					}else if(order.equals("2")){//热门
						order = "";
						where = " a.eaId = ea1.id";
						list = easyArService.selectByPageCounts(pageInfo, where, order,lat,lng);
					}else{//同城
						order = " order by distance";
						list = easyArService.selectByPageApiNew(pageInfo, where, order,lat,lng,null);
					}
					if(list.size() > 0){
						for(int i = 0 ; i < list.size() ; i ++){
							String videoUrl = list.get(i).get("videoUrl").toString();
							videoUrl = videoUrl.split(",")[0];
							list.get(i).put("videoUrl", videoUrl);
						}
						result.data.put("ar", list);
						result.data.put("pageInfo", pageInfo.getTotalPage());
						result.msg.status = 0;
						result.msg.desc = "获取成功";
					}else{
						result.msg.status = 1;
						result.msg.desc = "暂无数据";
					}
				}else{
					result.msg.status = 4;
					result.msg.desc = "参数格式不正确";
				}
			}else{
				result.msg.status = 3;
				result.msg.desc = "参数不能为空";
			}
		}else{
			result.msg.status = 3;
			result.msg.desc = "参数不能为空";
		}
		return result;
	}	
	
	
	/**
	 * 详情
	 * 作者： 张叶
	 * 创建时间：2018年7月21日  上午11:27:04
	 */
	@ResponseBody
	@RequestMapping(value = "/getDetail", method = RequestMethod.POST)
	public ApiResult getDetail(HttpServletRequest request,Long easyArId,String telphoneUuid) {
		ApiResult result = new ApiResult();
		Admin admin = safeSessionService.getCurrent(request);
		if(easyArId != 0 && telphoneUuid != null && !"".equals(telphoneUuid)){
			EasyAr ea = easyArService.selectInfoById(easyArId,telphoneUuid,admin);
			if(ea != null && !"".equals(ea)){
				Long categoryId = ea.getCategoryId();
				if(categoryId != null && !"".equals(categoryId)){
					Category c = categoryService.selectByPrimaryKey(categoryId);
					if(c != null && !"".equals(c)){
						result.data.put("category",c);
					}
				}
				String videoUrl = ea.getVideoUrl();
				videoUrl = videoUrl.split(",")[0];
				ea.setVideoUrl(videoUrl);
				result.data.put("easyAr",ea);
				result.msg.status = 0;
				result.msg.desc = "获取成功";
			}else{
				result.msg.status = 1;
				result.msg.desc = "暂无数据";
			}
		}else{
			result.msg.status = 3;
			result.msg.desc = "参数不能为空";
		}
		return result;
	}	
	
	
	/**
	 * 推荐列表
	 * 作者： 张叶
	 * 创建时间：2018年7月12日  下午5:02:33
	 */
	@ResponseBody
	@RequestMapping(value = "/recommendList", method = RequestMethod.POST)
	public ApiResult recommendList(String lat,String lng) {
		ApiResult result = new ApiResult();

		String where = " and active = 1 and status = 'on'";
		if(lat != null && !"".equals(lat) &&
				lng != null && !"".equals(lng)){
	        Region region = getRegionByLocation(String.format("%s,%s", lng, lat));
	        if (region == null) {
	            region = regionService.getRegionByCode("130101");
	            where += " and region_code like '" + region.getCode() + "%'";
	        }
		}
		List<EasyAr> list = easyArService.selectByWhere(where);
		if(list.size() > 0){
			for(int i = 0 ; i < list.size() ; i ++){
				String videoUrl = list.get(i).getVideoUrl();
				videoUrl = videoUrl.split(",")[0];
				list.get(i).setVideoUrl(videoUrl);
			}
			result.data.put("arList", list);
			result.msg.status = 0;
			result.msg.desc = "获取成功";
		}else{
			result.msg.status = 1;
			result.msg.desc = "暂无数据";
		}
		return result;
	}	
	
	
	/**
	 * 推荐列表
	 * 作者： 张叶
	 * 创建时间：2018年7月12日  下午5:02:33
	 */
	@ResponseBody
	@RequestMapping(value = "/myEasyAr", method = RequestMethod.GET)
	public ApiResult myEasyAr(HttpServletRequest request){
		ApiResult result = new ApiResult();
		Admin admin = safeSessionService.getCurrent(request);
		if(admin != null){
			String where = " and admin_id = " + admin.getId();
			List<EasyAr> list = easyArService.selectByWhere(where);
			if(list.size() > 0){
				result.data.put("ar", list);
				result.msg.status = 0;
				result.msg.desc = "获取成功";
			}else{
				result.msg.status = 1;
				result.msg.desc = "暂无作品";
			}
		} else {
			result.msg.status = 2;
			result.msg.desc = "当前登录已失效，请重新登录";
		}
		return result;
	}	
	
	


	/**
	 * 获取定位信息
	 * 作者： 张叶
	 * 创建时间：2016年11月17日  下午1:48:06
	 */
    public Region getRegionByLocation(String location) {
        List<Region> list = regionService.selectByWhere(" and status = 'on'");
        String key = "ff53d41333699e71213e01ed52a73761";
        String url = String.format("http://restapi.amap.com/v3/geocode/regeo?key=%s&location=%s&poitype=&radius=&extensions=all&batch=false&roadlevel=", key, location);
        String content = HttpUtil.requestGet(url);
        JSONObject json = JSONObject.parseObject(content);
        Region region = null;
        if ("1".equalsIgnoreCase(json.getString("status"))) {//正常
            JSONObject a = json.getJSONObject("regeocode").getJSONObject("addressComponent");

            String district = a.getString("district");
            String adcode = a.getString("adcode");
//            String address = json.getJSONObject("regeocode").getString("formatted_address");
            String city = a.getString("city");
            try {//匹配乡镇
                region = list.stream().filter(region1 -> region1.getName().contains(city)).findAny().get();
            } catch (NoSuchElementException e) {
            	
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (region == null) {//匹配城区
                try {
                    region = list.stream().filter(region1 -> 
                    region1.getName().contains(district)).findAny().get();
                } catch (NoSuchElementException e) {
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (region == null) {//未匹配到
                region = new Region();
                region.setLevel(3);
                region.setCode(adcode);
                region.setName(district);
                region.setStatus("on");
                region.setTitle(district);
            }
            if (region.getLevel() == 4) {
                region = regionService.getRegionByCode(region.getCode().substring(0, 6));
            } else if (region.getLevel() == 3) {
            	region = regionService.getRegionByCode(region.getCode());
            } else if (region.getLevel() == 2) {
            	region = regionService.getRegionByCode(region.getCode() + "01");
            }
        }
        return region;
    }

}
